using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Dare.Utilities.Drawing
{
    public class HexRGBConvert
    {
        public static string ToRGBColorHexString(Color color, bool withPrefix)
        {
            return (withPrefix ? "0x" : "") + 
                (color.R < 16 ? "0" : "") + ((int)color.R).ToString("x") +
                (color.G < 16 ? "0" : "") + ((int)color.G).ToString("x") + 
                (color.B < 16 ? "0" : "") + ((int)color.B).ToString("x");
        }

        public static string ToARGBColorHexString(Color color, bool withPrefix)
        {
            return (withPrefix ? "0x" : "") +
                (color.A < 16 ? "0" : "") + ((int)color.A).ToString("x") +
                (color.R < 16 ? "0" : "") + ((int)color.R).ToString("x") +
                (color.G < 16 ? "0" : "") + ((int)color.G).ToString("x") +
                (color.B < 16 ? "0" : "") + ((int)color.B).ToString("x");
        }

        public static Color ToColor(string hexString)
        {
            hexString = hexString.ToLower();
            if (hexString.StartsWith("0x")) hexString = hexString.Substring(2);
            if (hexString.Length > 8) hexString = hexString.Substring(0, 8);
            if (hexString.Length > 6)
            {
                return Color.FromArgb((int)uint.Parse(hexString, System.Globalization.NumberStyles.HexNumber));
            }
            else
            {
                uint a = 0xff000000;
                return Color.FromArgb((int)(a + int.Parse(hexString, System.Globalization.NumberStyles.HexNumber)));
            }
        }

        public static Color? ToColorSafely(string hexString)
        {
            try
            {
                if (!String.IsNullOrEmpty(hexString))
                {
                    return ToColor(hexString);
                }
            }
            catch { }
            return null;

        }
        public static Color ToColorSafely(string hexString, Color defaultColor)
        {
            try
            {
                if (!String.IsNullOrEmpty(hexString))
                {
                    return ToColor(hexString);
                }
            }
            catch { }
            return defaultColor;
        }
    }
}
